<?php
/**
 * Created by PhpStorm.
 * User: 李闯
 * Date: 2020/4/22
 * Time: 11:11
 * Content:关于商品和服务
 */

namespace app\index\controller;


use Redis\Redis;
use think\Db;

class BizproInfo extends Common
{

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 请求商品+服务分类
     */
    function getBizproClass()
    {
        # 分类-->   1->服务  2->商品   0->全查
        $type = input("post.type");
        # 操作标识  addServer-->添加服务工单时查询使用
        $mark = trim(input('post.mark'));
        # 商品分类初始化
        $pro = array();
        # 服务分类初始化
        $service = array();
        $redis = new Redis();
        if ($type == 2) {
            #商品
            $pro = $redis->hGetJson('getClass', 'pro');
            if (empty($pro)) {
                $pro = Db::table('pro_class')->field("id,id label,class_title text,2 type")->where('class_id = 0 and status = 1')->select();
                $redis->hSetJson('getClass', 'pro', $pro);
            }
            if (empty($mark)) {
                array_unshift($pro, array("label" => 0, "text" => "全部商品", "type" => 2));
            }
        }
        if ($type == 1 or $type == 0) {
            #服务
            $service = $redis->hGetJson('getClass', 'service');
            if (empty($service)) {
                $bizType = Db::table('biz')->where(array('id' => $this->bizId))->value('biz_type');
                if($bizType==2){
                    $_idWhere = "id in (select service_class_id from service where id in (select sb.service_id from service_biz sb where sb.biz_id = " . $this->bizId . "))";
                }else{
                    $_idWhere = '';
                }
                $service = Db::table('service_class')->field("id label,service_class_title text,1 type")
                    ->where('service_class_pid = 0')
                    ->where($_idWhere)
                    ->select();
                $redis->hSetJson('getClass', 'service', $service);
            }

            if (empty($mark) or $mark == 'addServer')
                array_unshift($service, array("label" => 0, "text" => "全部服务", "type" => 1));
//            if ($mark == 'addServer') {
//                array_push($service, array("label" => -1, "text" => "自定义服务", 'type' => 1));
//                array_push($service, array("label" => -2, "text" => "自定义商品", 'type' => 2));
//            }
        }
        $_return = array_merge_recursive($service, $pro);
        return array('status' => true, 'data' => $_return);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询商品或服务
     */
    function getBizproService()
    {
        # 搜索内容
        $search = trim(input('post.search'));
        $type = input('post.type'); //选择的分类 1服务 2商品
        $label = input('post.label') ?? 0;//选择的具体类别标识 商品分类id 或服务分类的id
        $page = input('post.page') ?? 0;
        $add_type = input('post.add_type') ?? 0;
        $listRows = 10;
        $pageMark = $page * $listRows;
        if (!empty($search) and $search != 'false' and $search != 'undefined') {
            $service = $this->getServicesInfo($search, 0, $pageMark,$add_type);
            $pro = $this->getProInfo($search, 0, $pageMark);
            $info = array_merge($service, $pro);
        } else {
            if ($type == 1) {
                #选择服务
                $info = $this->getServicesInfo($search, $label, $pageMark,$add_type);
            } else {
                #查询商品
                $info = $this->getProInfo($search, $label, $pageMark);
            }
        }
        if (!empty($info)) {
//            foreach ($info as $k => $v) {
//                $info[$k]['img'] = imgUrl($v['img']);
//            }
            return array('status' => true, 'data' => $info);
        } else {
            return array('status' => false, 'data' => array());
        }
    }

    /**
     * @param string $search
     * @param int $class
     * @param $pageMark
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询服务
     */
    function getServicesInfo($search = '', $class = 0, $pageMark,$add_type=0)
    {
        $_where = 'service_status = 1 and audit_status=2';
        if(!empty($add_type)){
            $_where.=" and s.add_type = ".$add_type;
        }
        $_searchWhere = null;
        $_field = 'if(service_title like "%' . $search . '%" or service_keyborder like "%' . $search . '%",1,0)';
        $_fieldWhere = null;
        if (!empty($search) and $search != 'false' and $search != 'undefined') {
            $_searchWhere = '(locate("' . $search . '",service_title) or locate("' . $search . '",service_keyborder))';
            $_num = mb_strlen($search);
            $searchInfo = preg_split("//u", $search, -1, PREG_SPLIT_NO_EMPTY);
            foreach ($searchInfo as $v) {
                if (is_null($_searchWhere)) {
                    $_searchWhere = '';
                } else {
                    $_searchWhere .= ' or (locate("' . $v . '",service_title) or locate("' . $v . '",service_keyborder))';
                }
                $_field .= ' + if((service_title like "%' . $v . '%" or service_keyborder like "%' . $v . '%"),1,0)';
            }
            $_field = '(' . $_field . ')';
            $_fieldWhere = '(' . $_field . '>= ' . $_num . ')';
//            $_where .= " and (service_title like '%" . $search . "%' or service_keyborder like '%" . $search . "%')";
        }
        $_field = $_field . ' keyWeight';
        if (!empty($class)) {
            $classInfo = Db::table('service_class')->field('id')->where('service_class_pid = '.$class.' or id = '.$class)->select();
            $classInfo = implode(',',array_column($classInfo,'id'));
            $_where .= " and service_class_id in (" . $classInfo.")";
        }
        $biz_where = " id in (select sb.service_id from service_biz sb where sb.biz_id = " . $this->bizId . ")";
        # 判断门店类型
        $bizType = Db::table('biz')->field('biz_type')->where(array('id' => $this->bizId))->value('biz_type');
        if ($bizType == 1) {
            $this->bizId = 0;
            $biz_where = '';
        }
        //(select discount from service_car_mediscount where service_id=s.id and car_level_id=1 and service_type =1 and biz_id = ' . $this->bizId . ') price,
        $_service = Db::table('service s')
            ->field('id,service_title title,if(locate("http",service_image)=0,CONCAT("' . config('ecarcoo.EcarsImgUrl') . '",service_image),service_image) img,
            if(add_type=1,"商品","服务") type,add_type,is_discount,
            (select sm.discount from service_car_mediscount sm where service_id=s.id and service_type = 2 and car_level_id = 1 and biz_id=' . $this->bizId . ') price_small, 
            (select sm.discount from service_car_mediscount sm where service_id=s.id and service_type = 2 and car_level_id = 2 and biz_id=' . $this->bizId . ') price_mid, 
            (select sm.discount from service_car_mediscount sm where service_id=s.id and service_type = 2 and car_level_id = 3 and biz_id=' . $this->bizId . ') price_large,
            (select if((min(discount)*(select discount from service_mediscount where member_level=8 and service_id=s.id))= max(discount),
            (max(discount)),(CONCAT_WS("-",convert((min(discount)*(select discount from service_mediscount where member_level=9 and service_id=s.id)),
            decimal(10,2)),max(discount)))) from service_car_mediscount 
                where service_id=s.id and biz_id=' . $this->bizId . ') price,
            ' . $_field)
            ->where(array( 's.is_del' => 2))
            ->where($_where)
            ->where($biz_where)
            ->where($_searchWhere)
            ->where($_fieldWhere)
            ->order(array('keyWeight' => 'desc'))
            ->order(array('service_order' => 'asc', 'id' => 'asc'))
            ->limit($pageMark, 10)
            ->select();
        return $_service;
    }

    /**
     * @param string $search
     * @param int $class
     * @param $pageMark
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查询商品
     */
    function getProInfo($search = '', $class = 0, $pageMark)
    {
        $_where = 'bp.biz_pro_type=0';
        if (!empty($search)) {
            $_where .= " and (bp.biz_pro_title like '%" . $search . "%' or bp.biz_pro_key like '%" . $search . "%')";
        }
        if (!empty($class)) {
            $class = getsBizProChildClass($class);
            if (!empty($class)) {
                $_where .= " and bp.biz_pro_class_id in (" . $class . ")";
            }
        }
        # 判断门店类型
        $bizType = Db::table('biz')->field('biz_type')->where(array('id' => $this->bizId))->value('biz_type');
        $biz_where = "bp.id in (select pro_id from biz_goods where biz_id = " . $this->bizId . ") ";
        if ($bizType == 1) {
            $this->bizId = 0;
            $biz_where = '';
        }
        $_proInfo = Db::table('biz_pro bp')
            ->field('id,biz_pro_title title,if(locate("http",biz_pro_image)=0,CONCAT("' . config('ecarcoo.EcarsImgUrl') . '",biz_pro_image),biz_pro_image) img,
            "商品" type,1 add_type,is_discount,
            (select goods_online from biz_goods where pro_id = bp.id and biz_id=' . $this->bizId . ') goods_online,
            (select goods_price from biz_goods where pro_id = bp.id and biz_id=' . $this->bizId . ') goods_price
            ')
            ->where($_where)
            ->where($biz_where)
            ->where("(select bi.number from biz_invent bi where bi.biz_id = " . $this->bizId . " and bi.biz_pro_id=bp.id and pro_type=1 limit 1) > 0")
            ->order(array('biz_pro_order' => 'asc', 'biz_pro_buy' => 'desc'))
            ->limit($pageMark, 10)
            ->select();
        return $_proInfo;
    }


    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 请求服务价格和折扣
     */
    function getServiceDetail()
    {
        #服务id
        $id = input("post.query_id");
        $_array = array();
        # 判断门店类型
        $bizType = Db::table('biz')->where(array('id' => $this->bizId))->find();
        if ($bizType['biz_type'] == 1) {
            $this->bizId = 0;
        }
        if (!empty($id)) {
            # 服务大中小车价格(门店价格)
            $local_car_discount = Db::table('service_car_mediscount sc')
                ->field('discount biz_price,cl.level_title car_type_text,sc.car_level_id car_type')
                ->join('car_level cl', 'cl.id = sc.car_level_id')
                ->where("sc.service_id = $id and sc.service_type = 2 ")
                ->where(array('sc.biz_id' => $this->bizId))
                ->order('sc.car_level_id asc')
                ->select();
            # 服务大中小车价格（线上价格)
            $online_car_discount = Db::table('service_car_mediscount sc')
                ->field('discount online_price,cl.level_title car_type_text,sc.car_level_id car_type ')
                ->join('car_level cl', 'cl.id = sc.car_level_id')
                ->where("sc.service_id = $id and sc.service_type = 1")
                ->where(array('sc.biz_id' => $this->bizId))
                ->order('sc.car_level_id asc')
                ->select();
            foreach ($local_car_discount as $k => $v) {
                $list[] = array_merge($v, $online_car_discount[$k]);
            }
            $_array['price'] = $list;
            # 查询服务对应会员折扣
            $member_discount = Db::table('service_mediscount sm')
                ->field('sm.discount,REPLACE (ml.level_title,"会员","") member_title,sm.member_level member_grade')
                ->join('member_level ml', 'ml.id = sm.member_level', 'left')
                ->where("sm.service_id = $id")
                ->order('member_level asc')->select();
            # 查询服务对应的服务提成比例
            if ($bizType['biz_type'] == 1) {
                # 直营店
                $_array['service_service'] = (Db::table('service')
                        ->field('service_commission')
                        ->where("id =$id")
                        ->value('service_commission')) * 100 . "%";
            } else {
                # 合作店
                $_array['service_service'] = $bizType['commission_platservice'] * 100 . "%";
            }
            # 推荐提成
            if ($bizType['biz_type'] == 1) {
                # 直营店
                $_array['service_recommend'] = (Db::table('service')
                        ->field('service_refer')
                        ->where("id =$id")
                        ->value('service_refer')) * 100 . '%';
            } else {
                # 合作店
                $_array['service_recommend'] = $bizType['recommond_commission_platservice'] * 100 . "%";
            }
            #服务时长
            $_array['service_time'] = Db::table('service')
                ->field('service_time')
                ->where("id =$id")
                ->value('service_time');
            #服务名称
//            $_array['service_title'] = $re_percent['service_title'];
            $_array['service_title'] = Db::table('service')->field('service_title')->where(array('id' => $id))->value('service_title');
            #会员折扣
            $_array['discount_list'] = $member_discount;
            if (!empty($_array)) {
                return array('status' => true, 'data' => $_array);
            } else {
                return array('status' => false, 'data' => array());
            }
        } else {
            return array('status' => false, 'msg' => '参数为空');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 请求商品价格和折扣
     */
    function getGoodsDetails()
    {
        #商品id
        $id = input("post.query_id");
        $_array = array();
        # 判断门店类型
        $bizType = Db::table('biz')->field('biz_type')->where(array('id' => $this->bizId))->value('biz_type');
        if ($bizType == 1) {
            $this->bizId = 0;
        }
        if (!empty($id)) {
            # 商品门店价，线上价
            $biz_pro = Db::table('biz_goods bg')
                ->field('bg.goods_price,bg.goods_online,bp.biz_pro_title')
                ->join('biz_pro bp', 'bp.id = bg.pro_id', 'left')
                ->where("pro_id = $id and  biz_id = $this->bizId")
                ->find();
            # 商品会员折扣
            $member_discount = Db::table('biz_pro_mediscount bp')
                ->field('bp.discount,ml.level_title member_title,bp.member_level member_grade')
                ->join('member_level ml', 'ml.id = bp.member_level', 'left')
                ->where("bp.biz_pro_id = $id")
                ->order("bp.member_level")
                ->select();
            #服务提成
            $pro_deduct = Db::table('station')
                ->field('min(biz_deduct) mind,max(biz_deduct) maxd')
                ->where(array('biz_id' => $this->bizId))
                ->find();
            $_array['goods_recommend'] = $pro_deduct['mind'] . "%~" . $pro_deduct['maxd'] . "%~";
            $_array['goods_service'] = $pro_deduct['mind'] . "%~" . $pro_deduct['maxd'] . "%~";
            #线上价格
            $_array['online_price'] = $biz_pro['goods_online'];
            #门店价格
            $_array['biz_price'] = $biz_pro['goods_price'];
            #商品名称
            $_array['name'] = $biz_pro['biz_pro_title'];
            $_array['discount_list'] = $member_discount;
            if (!empty($_array)) {
                return array('status' => true, 'data' => $_array);
            } else {
                return array('status' => false, 'data' => array());
            }
        } else {
            return array('status' => false, 'msg' => '参数为空');
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 通过手机号查询用户信息(昵称 , 手机号 , 余额 , 会员等级)
     */
    function getMemberInfo()
    {
        # 接收搜索信息
        $searchInfo = input('post.searchInfo');
        if (!empty($searchInfo)) {
            # 通过手机号查询用户信息
            $verification = checkMobile($searchInfo);
            if ($verification) {
                $info = Db::table('member m')
                    ->field('if(member_name is null or member_name ="",from_base64(m.nickname),member_name) name,m.member_phone phone,mm.member_balance balance,ml.level_title title')
                    ->join('member_mapping mm', 'mm.member_id=m.id', 'left')
                    ->join('member_level ml', 'mm.member_level_id=ml.id', 'left')
                    ->where(array('member_phone' => $searchInfo))
                    ->find();
                return array('status' => true, 'msg' => '查询成功', 'info' => $info);
            } else {
                return array('status' => false, 'msg' => '手机号不正确');
            }
        } else {
            return array('status' => false, 'msg' => '搜索条件为空');
        }
    }
}
